package com.hilog.productservice.controller;

import com.hilog.common.Result;
import com.hilog.productservice.feign.PaymentFeignClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 商品服务控制器
 */
@RestController
@RequestMapping("/product")
public class ProductController {

    private static final Logger log = LoggerFactory.getLogger(ProductController.class);

    @Autowired
    private PaymentFeignClient paymentFeignClient;

    /**
     * 测试接口
     */
    @GetMapping("/test")
    public String test() {
        return "商品服务启动成功！";
    }

    /**
     * 购买商品接口
     * @param productId 商品ID
     * @return 购买结果
     */
    @GetMapping("/buy/{productId}")
    public Map<String, Object> buyProduct(@PathVariable("productId") String productId) {
        log.info("开始购买商品，商品ID: {}", productId);

        try {
            // 获取当前traceId
            String traceId = MDC.get("traceId");
            log.info("当前traceId: {}", traceId);
            
            // 1. 模拟商品购买逻辑
            Map<String, Object> productResult = new HashMap<>();
            productResult.put("productId", productId);
            productResult.put("productName", "商品" + productId);
            productResult.put("price", 99.99);
            productResult.put("status", "购买成功");
            
            log.info("商品购买成功，商品ID: {}", productId);
            
            // 2. 生成订单ID
            String orderId = "ORDER_" + System.currentTimeMillis();
            log.info("生成订单ID: {}", orderId);
            
            // 3. 调用支付服务进行扣款
            log.info("调用支付服务进行扣款");
            Map<String, Object> paymentResult = paymentFeignClient.deductPayment(orderId, traceId);
            log.info("支付服务返回结果: {}", paymentResult);
            if ((Integer) paymentResult.get("code") != 200) {
                log.error("支付服务扣款失败，订单ID: {}", orderId);
                throw new RuntimeException("支付服务扣款失败");
            }
            // 4. 组装最终结果
            Map<String, Object> result = new HashMap<>();
            result.put("productId", productId);
            result.put("productName", "商品" + productId);
            result.put("price", 99.99);
            result.put("orderId", orderId);
            result.put("productStatus", "购买成功");
            result.put("paymentStatus", paymentResult.get("status"));
            result.put("paymentInfo", paymentResult);
            result.put("code", 200);
            result.put("message", "商品购买成功，支付扣款成功，商品ID: " + productId);
            
            log.info("商品购买和支付扣款都成功，商品ID: {}", productId);
            return result;
            
        } catch (Exception e) {
            log.error("商品购买失败，商品ID: {}", productId, e);
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("code", 500);
            errorResult.put("message", "商品购买失败: " + e.getMessage());
            return errorResult;
        }
    }

    /**
     * 健康检查接口
     */
    @GetMapping("/health")
    public Result<String> health() {
        return Result.success("商品服务运行正常");
    }
} 